package org.galaxyworld.flycode.core;

import org.apache.commons.io.FilenameUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;

import java.io.IOException;
import java.util.Map;

public class TemplateManager {

    private GroupTemplate groupTemplate;

    public static TemplateManager getInstance() {
        return TemplateManagerSingleton.INSTANCE;
    }

    public void setSharedVariables(Map<String, Object> sharedVariables) {
        groupTemplate.setSharedVars(sharedVariables);
    }

    public void appendSharedVariables(Map<String, Object> sharedVariables) {
        sharedVariables.putAll(groupTemplate.getSharedVars());
        groupTemplate.setSharedVars(sharedVariables);
    }

    public Template getTemplate(String name) {
        return groupTemplate.getTemplate(name);
    }

    private TemplateManager() {
        String root = FilenameUtils.separatorsToSystem(String.format("%s/templates", System.getProperty("user.dir")));
        FileResourceLoader resourceLoader = new FileResourceLoader(root, "utf-8");
        try {
            Configuration cfg = Configuration.defaultConfiguration();
            groupTemplate = new GroupTemplate(resourceLoader, cfg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static final class TemplateManagerSingleton {
        public static final TemplateManager INSTANCE = new TemplateManager();
    }

}
